import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:happy_elf_app/apis/home.dart';
import 'package:happy_elf_app/utils/adaption.dart';
import 'package:happy_elf_app/widgets/Toast/index.dart';

class breakDown extends StatefulWidget {
  final int taskId;
  final Function callBack;
  const breakDown({super.key, required this.callBack, required this.taskId});

  @override
  State<breakDown> createState() => _breakDownState();
}

class _breakDownState extends State<breakDown>
    with SingleTickerProviderStateMixin {
  int active = 1;
  var dialogState;
  int task = 0; // 当前显示的拆分的任务
  Map slider = {
    'difficulty': 1.0, // 难度 1-10
    'time': 1.0, // 时间 1-4
    'fun': 1.0, // 有趣值 1-10
  };
  // Map activeTask = {}; // 选中的任务
  Map activeStep = {}; // 选中的步骤
  Timer? _pollingTimer; // 定时器
  Map optimize = {}; // 拆分的任务数据
  Function? setModalState;
  late Timer _progressTimer; // 进度计时器
  Set<String> _selectedStepIds = Set(); // 存储选中的步骤id

  @override
  void initState() {
    super.initState();
    startPolling();
  }

  @override
  void dispose() {
    super.dispose();
    _cancelPolling();
    if (_progressTimer.isActive) {
      _progressTimer.cancel();
    }
    EasyLoading.dismiss(); // 确保页面销毁时关闭弹窗
    _controllers.forEach((taskIndex, subControllers) {
      subControllers.forEach((subIndex, controller) => controller.dispose());
    });
    _focusNodes.forEach((taskIndex, subNodes) {
      subNodes.forEach((subIndex, node) => node.dispose());
    });
  }

  late Map<int, Map<int, TextEditingController>> _controllers;
  // 存储每个子任务的焦点节点
  late Map<int, Map<int, FocusNode>> _focusNodes;
  // 当前聚焦的输入框位置
  List taskList = [];
  double sent = 0;

  void startPolling() {
    EasyLoading.showProgress(
      sent,
      status: '加载中$sent%',
    );
    // 立即执行一次查询（可选，避免等待第一个2秒）
    _queryAiTask();

    _progressTimer = Timer.periodic(const Duration(seconds: 2), (timer) {
      setState(() {
        if (sent < 99) {
          sent = (sent + 8).clamp(0, 99);
        } else {
          timer.cancel();
        }
      });

      EasyLoading.showProgress(
        sent / 100,
        status: '加载中${sent.toStringAsFixed(0)}%',
      );
    });

    // 启动定时器，每2秒执行一次
    _pollingTimer = Timer.periodic(const Duration(seconds: 2), (timer) {
      _queryAiTask();
    });
  }

// 实际查询接口的方法
  void _queryAiTask() async {
    try {
      var res = await Home().getAiTask(widget.taskId);
      print('AI接口返回数据: $res');
      if (res['code'] == 200 && res['data']['taskList'].length > 0) {
        _progressTimer.cancel();
        EasyLoading.dismiss();
        taskList = res['data']['taskList'];
        optimize = res['data'];
        sent = 100;
        setState(() {});
        _cancelPolling();
        _initControllers();
      }
    } catch (e) {
      print('接口请求异常: $e');
      _progressTimer.cancel();
      _cancelPolling();
      Toast.show(context: context, message: '接口请求异常');
      EasyLoading.dismiss();
    }
  }

// 取消定时器的方法
  void _cancelPolling() {
    if (_pollingTimer != null && _pollingTimer!.isActive) {
      _pollingTimer!.cancel();
      _pollingTimer = null;
    }
  }

  // 初始化所有子任务的控制器
  void _initControllers() {
    _controllers = {};
    _focusNodes = {};

    for (int taskIndex = 0; taskIndex < taskList.length; taskIndex++) {
      final task = taskList[taskIndex];
      final subTasks = task['stepList'] as List;
      _controllers[taskIndex] = {};
      _focusNodes[taskIndex] = {};

      for (int subIndex = 0; subIndex < subTasks.length; subIndex++) {
        final subTask = subTasks[subIndex];
        _controllers[taskIndex]![subIndex] = TextEditingController(
          text: subTask['name'] ?? '',
        );
        // 初始化焦点节点并添加监听
        final focusNode = FocusNode();
        focusNode.addListener(() {
          if (focusNode.hasFocus) {
            // 输入框获得焦点时，更新选中状态
            setState(() {
              activeStep = subTask;
            });
          }
        });
        _focusNodes[taskIndex]![subIndex] = focusNode;
      }
    }
  }

  Widget _buildTabItem(Map<String, dynamic> tab) {
    final bool isSelected = tab['value'] == active;
    return Expanded(
      child: GestureDetector(
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 8.80, vertical: 10),
          decoration: ShapeDecoration(
            color: isSelected ? Colors.white : const Color(0xFFF5F5F5),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10),
            ),
            // 只有选中项显示阴影
            shadows: isSelected
                ? [
                    const BoxShadow(
                      color: Color(0x0C000000),
                      blurRadius: 2.93,
                      offset: Offset(0, 2.93),
                      spreadRadius: 0,
                    )
                  ]
                : null,
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                tab['title'],
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: isSelected
                      ? const Color(0xFF3C3C3C)
                      : const Color(0xFF999999),
                  fontSize: 15,
                  fontFamily: 'Inter',
                  fontWeight: isSelected ? FontWeight.w700 : FontWeight.w500,
                  height: 0.98,
                ),
              ),
            ],
          ),
        ),
        onTap: () {
          setState(() {
            active = tab['value'];
            _syncControllersForTask(task);
            if (active == 1) {
              activeStep = {};
            }
          });
        },
      ),
    );
  }

  Widget _buildDivider() {
    return Container(
      color: Colors.grey,
      width: 1.px,
      height: 18.px,
      margin: EdgeInsets.symmetric(horizontal: 10.px),
    );
  }

  // 切换
  Widget typeBuild() {
    return Container(
      width: 343,
      // height: 40,
      padding: EdgeInsets.all(1.47),
      margin: EdgeInsets.symmetric(horizontal: 24),
      decoration: ShapeDecoration(
        color: const Color(0x99EEEEEE),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(10),
        ),
      ),
      child: Row(
        children: [
          _buildTabItem({'title': 'AI拆分', 'value': 1}),
          _buildDivider(),
          _buildTabItem({'title': '自由编辑', 'value': 2})
        ],
      ),
    );
  }

  Widget taskAIItem(item) {
    final bool isSelected = _selectedStepIds.contains(item['id'].toString());
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        setState(() {
          if (isSelected) {
            _selectedStepIds.remove(item['id'].toString());
          } else {
            _selectedStepIds.add(item['id'].toString());
          }
        });
      },
      child: Container(
        width: 309,
        margin: EdgeInsets.only(top: 10),
        padding: EdgeInsets.all(12),
        decoration: ShapeDecoration(
          color: isSelected
              ? Color.fromRGBO(255, 213, 213, 0.27)
              : Color.fromRGBO(255, 255, 255, 0.9),
          shape: RoundedRectangleBorder(
            side: BorderSide(
              width: 1,
              color: isSelected
                  ? hexColor('#FFB6AC')
                  : Color.fromRGBO(0, 0, 0, 0.2),
            ),
            borderRadius: BorderRadius.circular(10),
          ),
        ),
        child: Container(
          child: Text(item['name']),
        ),
      ),
    );
  }

  Widget taskItem(int taskIndex, int subIndex, Map item) {
    print('taskIndex00---$item---item$item');
    final bool isSelected = _selectedStepIds.contains(item['id'].toString());
    // _controllers[taskIndex]![subIndex] = item['name'];
    return GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          setState(() {
            if (isSelected) {
              _selectedStepIds.remove(item['id'].toString());
            } else {
              _selectedStepIds.add(item['id'].toString());
            }
          });
          _focusNodes[taskIndex]![subIndex]!.requestFocus();
        },
        child: Container(
          width: 309,
          margin: const EdgeInsets.only(top: 10),
          padding: const EdgeInsets.all(12),
          decoration: ShapeDecoration(
            color: isSelected
                ? const Color.fromRGBO(255, 213, 213, 0.27)
                : const Color.fromRGBO(255, 255, 255, 0.9),
            shape: RoundedRectangleBorder(
              side: BorderSide(
                width: 1,
                color: isSelected
                    ? const Color(0xFFFFB6AC)
                    : const Color.fromRGBO(0, 0, 0, 0.2),
              ),
              borderRadius: BorderRadius.circular(10),
            ),
          ),
          child: Focus(
            onFocusChange: (hafocus) async {
              var value = _controllers[taskIndex]![subIndex];
              print('value--${value!.text}---activeStep--$activeStep');
              if (!hafocus) {
                Map data = {"stepId": item['taskId'], "name": value.text};
                var res = await Home().updateStep(data);
                print('res$res');
              }
            },
            child: TextField(
              controller: _controllers[taskIndex]![subIndex],
              focusNode: _focusNodes[taskIndex]![subIndex],
              maxLines: 2,
              style: const TextStyle(
                fontSize: 15,
                height: 1.5,
                color: Color(0xFF333333),
              ),
              decoration: const InputDecoration(
                border: InputBorder.none,
                hintText: '请输入任务内容',
                hintStyle: TextStyle(color: Color(0xFF999999), fontSize: 15),
                contentPadding: EdgeInsets.zero,
                isDense: true,
                isCollapsed: true,
              ),
              onChanged: (value) {
                item['title'] = value;
                if (isSelected) {
                  setState(() {
                    _selectedStepIds.remove(item['id'].toString());
                    item['name'] = value;
                    _selectedStepIds.add(item['id'].toString());
                  });
                }
              },
            ),
          ),
        ));
  }

  Widget _buildEditableTaskName(int taskIndex) {
    final TextEditingController _controller = TextEditingController(
      text: taskList[taskIndex]['name'] ?? '未命名任务',
    );
    final FocusNode _focusNode = FocusNode();

    _focusNode.addListener(() async {
      if (!_focusNode.hasFocus) {
        print('taskList${taskList[taskIndex]}');
        final newName = _controller.text.trim();
        if (newName.isNotEmpty && newName != taskList[taskIndex]['name']) {
          // 这里调用接口更新名称
          Map data = {'taskId': taskList[taskIndex]['id'], 'name': newName};
          var res = await Home().updateTask(data);
          if (res['code'] == 200) {
            taskList[taskIndex]['name'] = newName;
            setState(() {});
          }
          print('修改任务名称$res');
        }
      }
    });

    return Container(
      width: double.infinity,
      height: 60,
      child: Row(
        children: [
          Text(
            '任务${task + 1}: ',
            style: const TextStyle(
              fontSize: 16,
              color: Color.fromARGB(255, 55, 55, 55),
            ),
          ),
          // 关键修复：用Expanded包裹TextField，使其宽度受父容器约束
          Expanded(
            child: TextField(
              controller: _controller,
              focusNode: _focusNode,
              style: const TextStyle(
                fontSize: 16,
                color: Color.fromARGB(255, 55, 55, 55),
              ),
              decoration: InputDecoration(
                border: InputBorder.none,
                hintText: '请输入任务名称',
                hintStyle: TextStyle(
                  fontSize: 16,
                  color: hexColor('#3d3d3d'),
                  fontWeight: FontWeight.normal,
                ),
                contentPadding: EdgeInsets.zero,
                isDense: true,
                enabledBorder: const UnderlineInputBorder(
                  borderSide: BorderSide(color: Colors.transparent),
                ),
              ),
              maxLength: 30,
              buildCounter: (context,
                      {required currentLength,
                      required isFocused,
                      maxLength}) =>
                  null,
              textInputAction: TextInputAction.done,
              onEditingComplete: () {
                _focusNode.unfocus();
              },
            ),
          ),
        ],
      ),
    );
  }

  // 内容
  Widget contentBuild() {
    return Container(
      width: 336,
      // height: 486,
      margin: EdgeInsets.only(top: 24),
      padding: EdgeInsets.all(20),
      decoration: ShapeDecoration(
          color: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
          shadows: const [
            BoxShadow(
              color: Color(0x19000000),
              blurRadius: 2.05,
              offset: Offset(3.08, 3.08),
              spreadRadius: 0,
            ),
            BoxShadow(
              color: Color(0x19000000),
              blurRadius: 2.05,
              offset: Offset(-3.08, -3.08),
              spreadRadius: 0,
            )
          ]),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          taskList.isNotEmpty ? _buildEditableTaskName(task) : SizedBox(),
          if (taskList.isNotEmpty)
            for (int subIndex = 0;
                subIndex < taskList[task]['stepList'].length;
                subIndex++)
              active == 1
                  ? taskAIItem(taskList[task]['stepList'][subIndex])
                  : taskItem(
                      task,
                      subIndex,
                      taskList[task]['stepList'][subIndex],
                    ),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextButton(
                onPressed: () {
                  if (task > 0) {
                    setState(() {
                      task -= 1;
                      _selectedStepIds.clear();
                      _syncControllersForTask(task);
                    });
                  }
                },
                child: Text(
                  "<",
                  style:
                      TextStyle(color: task == 0 ? Colors.grey : Colors.black),
                ),
              ),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 24),
                child: Text("${task + 1}/${taskList.length}"),
              ),
              TextButton(
                onPressed: () {
                  if (task < taskList.length - 1) {
                    setState(() {
                      task += 1;
                    });
                  }
                },
                child: Text(">",
                    style: TextStyle(
                        color: task == taskList.length - 1
                            ? Colors.grey
                            : Colors.black)),
              ),
            ],
          ),
          Center(
            child: GestureDetector(
              child: Container(
                width: 169,
                margin: EdgeInsets.only(top: 24),
                padding: EdgeInsets.symmetric(vertical: 10),
                decoration: ShapeDecoration(
                  color: hexColor('#e9614d'),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(30),
                  ),
                  shadows: const [
                    BoxShadow(
                      color: Color(0x0C000000),
                      blurRadius: 2.93,
                      offset: Offset(0, 2.93),
                      spreadRadius: 0,
                    )
                  ],
                ),
                child: Center(
                  child: Text(
                    active == 2 ? '编辑此阶段' : '优化此阶段',
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 16,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w600,
                      height: 1.06,
                    ),
                  ),
                ),
              ),
              onTap: () {
                if (active == 1) {
                  showTaskDialog(context: context, type: 'only');
                }
              },
            ),
          )
        ],
      ),
    );
  }

  // 同步指定任务组的控制器与数据源
  void _syncControllersForTask(int taskIndex) {
    if (taskList.isEmpty || taskIndex >= taskList.length) return;
    final currentTask = taskList[taskIndex];
    final subTasks = currentTask['stepList'] as List;

    // 确保控制器已初始化
    if (!_controllers.containsKey(taskIndex)) {
      _controllers[taskIndex] = {};
    }

    for (int subIndex = 0; subIndex < subTasks.length; subIndex++) {
      final subTask = subTasks[subIndex];
      // 确保子控制器已初始化
      if (!_controllers[taskIndex]!.containsKey(subIndex)) {
        _controllers[taskIndex]![subIndex] =
            TextEditingController(text: subTask['name'] ?? '');
      }
      final currentText = _controllers[taskIndex]![subIndex]!.text;
      // 仅当数据源与控制器文本不一致时更新
      if (subTask['name'] != currentText) {
        _controllers[taskIndex]![subIndex]!.text = subTask['name'] ?? '';
      }
    }
  }

  // 同步所有任务的控制器与数据源
  void _syncAllControllers() {
    for (int taskIndex = 0; taskIndex < taskList.length; taskIndex++) {
      _syncControllersForTask(taskIndex);
    }
  }

// 优化弹窗
  void showTaskDialog({required BuildContext context, required String type}) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: ((context, dialogSetState) {
            setModalState = dialogSetState;
            return Align(
              alignment: Alignment.topCenter,
              child: Container(
                margin: EdgeInsets.only(
                  top: MediaQuery.of(context).size.height * 0.5 - 24,
                ),
                width: 340,
                height: type == 'all' ? 280 : 230, // 适配是否显示时间滑块
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(10),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.grey.withOpacity(0.5),
                      spreadRadius: 2,
                      blurRadius: 5,
                      offset: const Offset(0, 3),
                    ),
                  ],
                ),
                child: Column(
                  children: [
                    const Padding(
                      padding: EdgeInsets.only(top: 15, bottom: 10),
                      child: Text(
                        '请选择优化的方向',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    // 困难度滑块（4段：1-2-3-4）
                    _buildSegmentedSlider(
                      title: '简单',
                      endTitle: '困难',
                      value: slider['difficulty']!,
                      onChanged: (value) {
                        print('1111--1-1-$value');
                        dialogSetState(() {
                          slider['difficulty'] = value;
                        });
                      },
                    ),
                    SizedBox(height: 6),
                    if (type == 'all')
                      // 时间滑块（4段：1-2-3-4周）
                      _buildSegmentedSlider(
                        title: '一周',
                        endTitle: '四周',
                        value: slider['time']!,
                        onChanged: (value) {
                          dialogSetState(() {
                            slider['time'] = value;
                          });
                        },
                      ),
                    SizedBox(height: 6),
                    // 趣味性滑块（4段：1-2-3-4）
                    _buildSegmentedSlider(
                      title: '有趣',
                      endTitle: '标准',
                      value: slider['fun']!,
                      onChanged: (value) {
                        dialogSetState(() {
                          slider['fun'] = value;
                        });
                      },
                    ),
                    Padding(
                      padding: const EdgeInsets.symmetric(
                          horizontal: 15, vertical: 10),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          ElevatedButton(
                            onPressed: () {
                              Navigator.of(context).pop();
                              // 重置滑块（放在setState外，避免弹窗已销毁导致异常）
                              slider = {
                                'difficulty': 1.0,
                                'time': 1.0,
                                'fun': 1.0,
                              };
                            },
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.white,
                              foregroundColor: Colors.black,
                              side: BorderSide(color: hexColor('#ededed')),
                              minimumSize: const Size(100, 40), // 统一按钮大小
                            ),
                            child: const Text('关闭'),
                          ),
                          ElevatedButton(
                            onPressed: () async {
                              print(
                                  '提交优化参数：$slider---$type--$activeStep, ==${task}');
                              // 重置滑块
                              slider = {
                                'difficulty': 1.0,
                                'time': 1.0,
                                'fun': 1.0,
                              };
                              EasyLoading.show(status: '加载中...');
                              if (type == 'all') {
                                // 优化全局
                                Map data = {
                                  "targetId": taskList[task]['targetId'],
                                  "duration": slider['time'],
                                  "difficulty": slider['difficulty'],
                                  "fun": slider['fun']
                                };
                                try {
                                  var res = await Home().optimizePreview(data);
                                  print('res888-$res');
                                  if (res['code'] == 200) {
                                    optimize = res['data'];
                                    taskList = res['data']['taskList'];
                                    setState(() {});
                                    Navigator.of(context).pop();
                                  }
                                  EasyLoading.dismiss();
                                } catch (e) {
                                  EasyLoading.dismiss();
                                }
                              } else {
                                if (_selectedStepIds.isEmpty) {
                                  Toast.show(
                                      context: context, message: '请至少选择一个任务项');
                                  return;
                                }
                                // 收集所有选中项的 stepList
                                List<Map> selectedSteps = [];
                                for (var task in taskList) {
                                  for (var step in task['stepList']) {
                                    if (_selectedStepIds
                                        .contains(step['id'].toString())) {
                                      selectedSteps.add({
                                        'id': step['id'],
                                        'name': step['name'],
                                      });
                                    }
                                  }
                                }
                                print('_selectedStepIds--$_selectedStepIds');
                                print('selectedSteps--$selectedSteps');
                                print('taskList[task]---${taskList[task]}');
                                // 优化步骤
                                Map data = {
                                  'targetId': taskList[task]['targetId'],
                                  "taskId": taskList[task]['id'],
                                  "difficulty": slider['difficulty'],
                                  "fun": slider['fun'],
                                  'stepList': selectedSteps
                                };
                                try {
                                  var res = await Home().optimizeStep(data);
                                  print('res$res');
                                  if (res['code'] == 200) {
                                    for (var updatedStep in res['data']
                                        ['steps']) {
                                      for (var task in taskList) {
                                        int index = task['stepList'].indexWhere(
                                          (item) =>
                                              item['id'] == updatedStep['id'],
                                        );
                                        if (index != -1) {
                                          task['stepList'][index]['name'] =
                                              updatedStep['newName'];
                                        }
                                      }
                                    }
                                    setState(() {
                                      _selectedStepIds.clear(); // 清空选中状态
                                    });
                                    // Navigator.of(context).pop();
                                  }
                                  EasyLoading.dismiss();
                                  Navigator.of(context).pop();
                                } catch (e) {
                                  EasyLoading.dismiss();
                                }
                              }
                            },
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.red,
                              minimumSize: const Size(100, 40), // 统一按钮大小
                            ),
                            child: const Text('确定'),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            );
          }),
        );
      },
    );
  }

  Widget _buildSegmentedSlider({
    required String title,
    required String endTitle,
    required double value,
    required ValueChanged<double> onChanged,
  }) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 0),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text(
                title,
                style: TextStyle(fontSize: 14, color: hexColor('#666666')),
              ),
              Expanded(
                child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: 12),
                  child: SliderTheme(
                    data: SliderThemeData(
                      trackHeight: 16.0, // 轨道高度10px
                      activeTrackColor: hexColor('#e9614d'), // 激活部分颜色
                      inactiveTrackColor: Colors.white, // 底色白色
                      // 隐藏刻度节点
                      activeTickMarkColor: Colors.transparent,
                      inactiveTickMarkColor: Colors.transparent,
                      thumbColor: Colors.white,
                      // 使用带阴影的自定义滑块
                      thumbShape: CustomRectangularThumbShape(
                        width: 12.0,
                        height: 26.0,
                      ),
                      // 使用带阴影的轨道
                      trackShape: const ShadowedRectangularTrackShape(),
                      overlayColor: Colors.transparent, // 去掉点击光晕
                      showValueIndicator: ShowValueIndicator.never, // 不显示标签
                    ),
                    child: Slider(
                      value: value,
                      min: 0,
                      max: 4,
                      divisions: 4,
                      label: null,
                      onChanged: (double value) {
                        print('当前进度：$value');
                        onChanged(value);
                      },
                    ),
                  ),
                ),
              ),
              Text(
                endTitle,
                style: TextStyle(fontSize: 14, color: hexColor('#666666')),
              ),
            ],
          ),
        ],
      ),
    );
  }

  // 辅助方法：十六进制颜色转换（确保hexColor方法可用）
  Color hexColor(String hex) {
    final hexCode = hex.replaceAll('#', '');
    return Color(int.parse('FF$hexCode', radix: 16));
  }

  // 重新生成确认弹窗
  // void showAgainDialog(context) {
  //   showDialog(
  //       context: context,
  //       builder: (BuildContext context) {
  //         return AlertDialog(
  //           content: Container(
  //             width: 340,
  //             height: 144,
  //             decoration: BoxDecoration(
  //               color: Colors.white,
  //               borderRadius: BorderRadius.all(
  //                 Radius.circular(20.px),
  //               ),
  //             ),
  //             child: Column(
  //               crossAxisAlignment: CrossAxisAlignment.center,
  //               children: [
  //                 Text('是否根据此AI方向'),
  //                 Row(
  //                   crossAxisAlignment: CrossAxisAlignment.center,
  //                   mainAxisAlignment: MainAxisAlignment.center,
  //                   children: [
  //                     Text('将'),
  //                     Text('全部任务',
  //                         style: TextStyle(color: hexColor('#e9614d'))),
  //                     Text('重新生成'),
  //                   ],
  //                 ),
  //                 SizedBox(height: 36),
  //                 Padding(
  //                   padding: const EdgeInsets.symmetric(horizontal: 15),
  //                   child: Row(
  //                     mainAxisAlignment: MainAxisAlignment.spaceBetween,
  //                     children: [
  //                       ElevatedButton(
  //                         onPressed: () {
  //                           Navigator.of(context).pop();
  //                         },
  //                         style: ElevatedButton.styleFrom(
  //                           backgroundColor: Colors.red,
  //                         ),
  //                         child: const Text('拒绝'),
  //                       ),
  //                       ElevatedButton(
  //                         onPressed: () {
  //                           Navigator.of(context).pop();
  //                           slider = {
  //                             'difficulty': 1.0,
  //                             'time': 1.0,
  //                             'fun': 1.0,
  //                           };
  //                         },
  //                         style: ElevatedButton.styleFrom(
  //                           backgroundColor: Colors.white,
  //                           foregroundColor: Colors.black,
  //                           side: BorderSide(color: hexColor('#ededed')),
  //                         ),
  //                         child: const Text('确定'),
  //                       ),
  //                     ],
  //                   ),
  //                 ),
  //               ],
  //             ),
  //           ),
  //         );
  //       });
  // }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: [
          typeBuild(),
          contentBuild(),
          SizedBox(height: 12),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextButton(
                  onPressed: () {
                    showTaskDialog(context: context, type: 'all');
                  },
                  child: Container(
                    padding: EdgeInsets.symmetric(
                        horizontal: 32.px, vertical: 15.px),
                    decoration: ShapeDecoration(
                      color: Colors.white,
                      shape: RoundedRectangleBorder(
                        side: const BorderSide(
                          width: 1,
                          color: Color.fromRGBO(0, 0, 0, 0.1),
                        ),
                        borderRadius: BorderRadius.circular(6.61),
                      ),
                      shadows: const [
                        BoxShadow(
                          color: Color(0x0C000000),
                          blurRadius: 2.41,
                          offset: Offset(0, 2.41),
                          spreadRadius: 0,
                        )
                      ],
                    ),
                    child: const Text(
                      "智能优化",
                      style: TextStyle(color: Color(0xFF020202)),
                    ),
                  )),
              active == 2
                  ? TextButton(
                      onPressed: () {
                        // 导入参考 // 此功能暂未开放
                        showDialog(
                          context: context,
                          builder: (BuildContext context) {
                            return StatefulBuilder(
                              builder: ((context, dialogSetState) {
                                return Align(
                                  alignment: Alignment.topCenter,
                                  child: Container(
                                    margin: EdgeInsets.only(
                                      top: MediaQuery.of(context).size.height *
                                              0.5 -
                                          48,
                                    ),
                                    width: 340,
                                    height: 220,
                                    decoration: BoxDecoration(
                                      color: Colors.white,
                                      borderRadius: BorderRadius.circular(10),
                                      boxShadow: [
                                        BoxShadow(
                                          color: Colors.grey.withOpacity(0.5),
                                          spreadRadius: 2,
                                          blurRadius: 5,
                                          offset: const Offset(0, 3),
                                        ),
                                      ],
                                    ),
                                    child: Column(
                                      children: [
                                        const Padding(
                                          padding: EdgeInsets.only(
                                              top: 55, bottom: 30),
                                          child: Text(
                                            '此功能暂未开放',
                                            style: TextStyle(
                                              fontSize: 18,
                                              fontWeight: FontWeight.bold,
                                            ),
                                          ),
                                        ),
                                        Padding(
                                          padding: const EdgeInsets.symmetric(
                                              horizontal: 15, vertical: 10),
                                          child: Row(
                                            mainAxisAlignment:
                                                MainAxisAlignment.spaceBetween,
                                            children: [
                                              ElevatedButton(
                                                onPressed: () {
                                                  Navigator.of(context).pop();
                                                },
                                                style: ElevatedButton.styleFrom(
                                                  backgroundColor: Colors.white,
                                                  foregroundColor: Colors.black,
                                                  side: BorderSide(
                                                      color:
                                                          hexColor('#ededed')),
                                                  minimumSize: const Size(
                                                      100, 40), // 统一按钮大小
                                                ),
                                                child: const Text('关闭'),
                                              ),
                                              ElevatedButton(
                                                onPressed: () async {
                                                  Navigator.of(context).pop();
                                                },
                                                style: ElevatedButton.styleFrom(
                                                  backgroundColor:
                                                      hexColor('#e9614d'),
                                                  minimumSize: const Size(
                                                      100, 40), // 统一按钮大小
                                                ),
                                                child: const Text('确定'),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                );
                              }),
                            );
                          },
                        );
                      },
                      child: Container(
                        padding: EdgeInsets.symmetric(
                            horizontal: 32.px, vertical: 15.px),
                        decoration: ShapeDecoration(
                          color: Colors.white,
                          shape: RoundedRectangleBorder(
                            side: const BorderSide(
                              width: 1,
                              color: Color.fromRGBO(0, 0, 0, 0.1),
                            ),
                            borderRadius: BorderRadius.circular(6.61),
                          ),
                          shadows: const [
                            BoxShadow(
                              color: Color(0x0C000000),
                              blurRadius: 2.41,
                              offset: Offset(0, 2.41),
                              spreadRadius: 0,
                            )
                          ],
                        ),
                        child: const Text(
                          "导入参考",
                          style: TextStyle(color: Colors.black),
                        ),
                      ))
                  : Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 10),
                      child: GestureDetector(
                        child: Image.asset(
                          'lib/assets/images/home/refresh.png',
                          width: 40,
                          height: 40,
                        ),
                        onTap: () {
                          // showAgainDialog(context);
                        },
                      ),
                    ),
              TextButton(
                  onPressed: () async {
                    var res = await Home().subOptimize(optimize);
                    print('提交任务拆分$res');
                    if (res['code'] == 200) {
                      Toast.show(context: context, message: '任务提交成功');
                      widget.callBack(optimize['id']);
                    }
                  },
                  child: Container(
                    padding: EdgeInsets.symmetric(
                        horizontal: 32.px, vertical: 15.px),
                    decoration: ShapeDecoration(
                      color: hexColor('#e9614d'),
                      shape: RoundedRectangleBorder(
                        side: const BorderSide(
                          width: 1,
                          color: Color.fromRGBO(0, 0, 0, 0.1),
                        ),
                        borderRadius: BorderRadius.circular(6.61),
                      ),
                      shadows: const [
                        BoxShadow(
                          color: Color(0x0C000000),
                          blurRadius: 2.41,
                          offset: Offset(0, 2.41),
                          spreadRadius: 0,
                        )
                      ],
                    ),
                    child: Text(
                      "    完成    ",
                      style: TextStyle(color: Colors.white),
                    ),
                  )),
            ],
          )
        ],
      ),
    );
  }
}

class CustomRectangularThumbShape extends SliderComponentShape {
  final double width;
  final double height;
  final double shadowBlur;
  final Color shadowColor;

  const CustomRectangularThumbShape({
    this.width = 12.0,
    this.height = 26.0,
    this.shadowBlur = 4.0,
    this.shadowColor = const Color.fromRGBO(0, 0, 0, 0.2),
  });

  @override
  Size getPreferredSize(bool isEnabled, bool isDiscrete) {
    return Size(width, height + shadowBlur);
  }

  @override
  void paint(
    PaintingContext context,
    Offset center, {
    required Animation<double> activationAnimation,
    required Animation<double> enableAnimation,
    required bool isDiscrete,
    required TextPainter labelPainter,
    required RenderBox parentBox,
    required SliderThemeData sliderTheme,
    required TextDirection textDirection,
    required double value,
    required double textScaleFactor,
    required Size sizeWithOverflow,
  }) {
    final canvas = context.canvas;
    final rect = Rect.fromCenter(
      center: center,
      width: width,
      height: height,
    );

    // 绘制滑块阴影
    final shadowPaint = Paint()
      ..color = shadowColor
      ..maskFilter = MaskFilter.blur(BlurStyle.normal, shadowBlur);
    canvas.drawRect(rect.shift(Offset(0, 2)), shadowPaint);

    // 绘制滑块本体
    final thumbPaint = Paint()..color = sliderTheme.thumbColor!;
    canvas.drawRect(rect, thumbPaint);
  }
}

class ShadowedRectangularTrackShape extends SliderTrackShape {
  final double shadowBlur;
  final Color shadowColor;

  const ShadowedRectangularTrackShape({
    this.shadowBlur = 3.0,
    this.shadowColor = const Color.fromRGBO(0, 0, 0, 0.1),
  });

  @override
  Rect getPreferredRect({
    required RenderBox parentBox,
    Offset offset = Offset.zero,
    required SliderThemeData sliderTheme,
    bool isEnabled = false,
    bool isDiscrete = false,
  }) {
    // 计算轨道尺寸（高度10px，宽度占满父容器）
    final trackHeight = sliderTheme.trackHeight ?? 10.0;
    final trackLeft = offset.dx;
    final trackTop = offset.dy + (parentBox.size.height - trackHeight) / 2;
    final trackWidth = parentBox.size.width;
    return Rect.fromLTWH(trackLeft, trackTop, trackWidth, trackHeight);
  }

  @override
  void paint(
    PaintingContext context,
    Offset offset, {
    required RenderBox parentBox,
    required SliderThemeData sliderTheme,
    required Animation<double> enableAnimation,
    required TextDirection textDirection,
    required Offset thumbCenter,
    Offset? secondaryOffset,
    bool isDiscrete = false,
    bool isEnabled = false,
  }) {
    final canvas = context.canvas;
    final trackRect = getPreferredRect(
      parentBox: parentBox,
      offset: offset,
      sliderTheme: sliderTheme,
      isEnabled: isEnabled,
      isDiscrete: isDiscrete,
    );
    final shadowPaint = Paint()
      ..color = shadowColor
      ..maskFilter = MaskFilter.blur(BlurStyle.normal, shadowBlur);
    canvas.drawRRect(
      RRect.fromRectAndRadius(trackRect, Radius.circular(2)),
      shadowPaint,
    );

    // 2. 绘制轨道背景（白色）
    final inactivePaint = Paint()..color = sliderTheme.inactiveTrackColor!;
    canvas.drawRRect(
      RRect.fromRectAndRadius(trackRect, Radius.circular(2)),
      inactivePaint,
    );

    final activeRect = Rect.fromLTWH(
      trackRect.left,
      trackRect.top,
      thumbCenter.dx - trackRect.left, // 激活部分宽度随滑块位置变化
      trackRect.height,
    );
    final activePaint = Paint()..color = sliderTheme.activeTrackColor!;
    canvas.drawRRect(
      RRect.fromRectAndRadius(activeRect, Radius.circular(2)),
      activePaint,
    );
  }
}
